#Programmer: Rory Carmichael
#Program: min_max_pipe.py
#Purpose: Weaver script to pipeline and distribute min-max and peak find for a single ORFeome
#NOTE: 8/14/2012 refactoring for new weaver and new pipeline
#Usage: rc-min_max_pipe.py <ORFeome.fasta> <num_rrts>

import shlex, subprocess
from weaver.nest import Nest
from weaver.function import PythonFunction, Function
from array import array
import re
import sys

def usage(): 
	print "Usage: weaver.py min_max_pipe.py <ORFeome.fasta> <num_rrts>\n"

if len(CurrentScript().arguments) != 2:
	usage()
	sys.exit(1)

#Pile of functions
calc_codon_usage = Function('rc-get-codon-frequency.pl', cmd_format = "{executable} {inputs} > {outputs}")
discretize = Function('rc-discretize-mm.pl', cmd_format = "{executable} {inputs} > {outputs}")
cat = Function('cat', cmd_format = "{executable} {inputs} > {outputs}")
#make_ci = Function('rc-count-codon-gc3-bins.pl', cmd_format = '{executable} {inputs} {outputs}')
#make_rrt = Function('rc-gc3-rrt-gen.pl', cmd_format = '{executable} {inputs} {outputs}')
min_max = Function('rc-min-max.pl', cmd_format = "{executable} {inputs} > {outputs}")
tar = Function('tar', cmd_format = '{executable} -czf {outputs} {inputs} --remove-files')
make_cm = Function('CodonMultipliers.pl', cmd_format = "{executable} {inputs} {outputs}")
make_gc3 = Function('CodonPrintGC3.pl', cmd_format = "{executable} {inputs} {outputs}")
make_rrt = Function('RRTsReadCodonListGC3.pl', cmd_format = "{executable} {inputs} {outputs}")

rrtfiles = []
rrtmm = []
orfeome = CurrentScript().arguments[0]
num_rrts = int(CurrentScript().arguments[1])

#Sneak the codon frequency file into the map-reduce stuff
cf = str(orfeome) . ".cf"
mm = str(orfeome) . ".mm"
dmm = str(orfeome) . ".dmm"
calc_codon_usage(inputs=orfeome, outputs=cf, local=True)
min_max( inputs=orfeome, outputs=mm)
discretize( inputs=mm, outputs=dmm)
#ci_out = str(orfeome) + ".counts"
cm_out = str(orfeome) + ".multipliers"
gc3_out = str(orfeome) + ".gc3"
rrt_out = str(orfeome) + ".rrt"
tar_out = str(orfeome) + ".tgz"
#make_ci(inputs=orfeome,outputs=ci_out)
make_cm(inputs=orfeome,outputs=cm_out)
make_gc3(inputs=[orfeome,cm_out], outputs=gc3_out)
make_rrt(inputs=[orfeome,gc3_out], outputs=rrt_out)
#It seems as if the rrt program makes one file with all 200 RRTs... weird, but okay
#for i in range(num_rrts):
#	#Maybe this should be one of those "pipeline" things
#	curout = str(orfeome) + "." + str(i) + ".fasta"
#	curstat = str(orfeome) + "." + str(i) + ".stat"
#	curmm = str(orfeome) + "." + str(i) + ".mm"
#	curdmm = str(orfeome) + "." + str(i) + ".dmm"
#	rrt_list.append(curout)
#	rrt_list.append(curstat)
#	make_rrt(inputs=[orfeome,ci_out], outputs=[curstat,curout])
#	min_max(inputs=[orfeome,cf], outputs=curmm)
#	discretize(inputs=curmm, outputs=curdmm)
